# -*- coding: utf-8 -*-
# 作者本人不熟悉python
# 以下代码仅用来测试
# 私钥加密不支持
# 私钥签名OK
# 公钥加密OK

import rsa
import base64


# 加密算法
def rsa_encrypt(message: str, publicKey):
    encrypt_message = rsa.encrypt(message.encode('UTF-8'), publicKey)
    return encrypt_message


# 解密算法
def rsa_decrypt(message, privateKey):
    message_str = rsa.decrypt(message, privateKey).decode()
    return message_str


# 公钥和私钥
# 这里只支持pkcs1格式
with open('public_key.pem', 'r') as f:
    publicKey = rsa.PublicKey.load_pkcs1(f.read().encode())
with open('private_key.pem', 'r') as f:
    privateKey = rsa.PrivateKey.load_pkcs1(f.read().encode())

# 公钥加密私钥解密
data = "www.apiext.com;www.apiext.cn"
encript_data = rsa_encrypt(data, publicKey)
print("---------------------------公钥加密,私钥解密字符串-------------------------")
print(str(base64.b64encode(encript_data), "UTF-8"))
message = rsa_decrypt(encript_data, privateKey)
print(message)


# python 使用pkcs1的私钥解密java pkcs8的公钥加密的数据
javaPublicPkcs8EncodeStr = 'D4ssHuwOSx+QhJGlloI1+Vy6OezIdk48AGm2OYUPvk8EhxQlwAI4DPl8Myt5HtOhDqWU4nGMF+dHADoL5OHIBBjj+95KtYQzkSPoicwY8LPyfhqwXgbPoziVdek3nUF+JAT0zItc5JKJ7dDe4O7fE1wY7CXd6qechhHXIU/CmHY='
javaPublicPkcs8DecoderBytes = base64.b64decode(javaPublicPkcs8EncodeStr)
print(javaPublicPkcs8DecoderBytes)
message = rsa_decrypt(javaPublicPkcs8DecoderBytes, privateKey)
print("解密java %s" % message)

# 签名
signStr = rsa.sign("中国".encode('UTF-8'), privateKey, 'SHA-256')
print(str(base64.b64encode(signStr), "UTF-8"))
hashMethod = rsa.verify("中国".encode('UTF-8'), signStr, publicKey)
print(hashMethod)
